import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
from yanloushi.settings import *
from celery.task import task
from time import sleep
from django.contrib.auth.hashers import make_password,check_password


# 定义发送邮件的方法
@task
def mail(subject, content, mailaddr):
    sleep(5)
    res = True
    try:
        # 声明邮件对象
        msg = MIMEText(content, 'plain', 'utf-8')

        # 设置发送方对象
        msg['From'] = formataddr(['实验二楼', my_mail])

        # 设置收件方对象
        msg['To'] = formataddr(['尊敬的客户', mailaddr])

        # 设置标题
        msg['Subject'] = subject

        # 设置smtp服务器
        server = smtplib.SMTP_SSL("smtp.qq.com", 465)

        # 登录邮箱
        server.login(my_mail, my_pass)

        # 发送邮件
        server.sendmail(my_mail, [mailaddr], msg.as_string())

        # 关闭smtp链接
        server.quit()
    except Exception as e:
        print(e)
        res = False
        return res
    return res



# # 加密
# def make_password(mypass):
#     # 生成md5对象
#     md5 = hashlib.md5()
#     # 定义机密对象
#     sign_str = str(mypass)
#     # 进行转码
#     sign_utf8 = sign_str.encode(encoding="utf-8")
#     # 加密
#     md5.update(sign_utf8)
#     # 生成密钥
#     md5_server = md5.hexdigest()
#     return md5_server


# 生成随机名
import random


def get_name():
    data = 'qwertyuioasdfghhjklzxcvbnmQWERTYUIOASDFGHJKLZXCVBNM1234567890'

    name = ''
    for i in range(14):
        char = random.choice(data)
        name += char

    return name

import time, jwt


def make_jwt(id):
    plyload = {
        'iss': '实验二楼',
        'iat': int(time.time()),
        'exp': int(time.time()) + 3000,
        'uid': id,
    }

    key = jwt.encode(plyload, 'jiang', algorithm='HS256')
    return key.decode('utf8')


# 验证jwt

def verify_jwt(token):
    try:
        data = jwt.decode(token, 'jiang', algorithms='HS256')

        return data['uid']
    except:
        return False

